package com.xzh.gulimall.product.web;

import com.xzh.gulimall.product.entity.CategoryEntity;
import com.xzh.gulimall.product.service.CategoryService;
import com.xzh.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class indexController {
    @Autowired
    CategoryService categoryService;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    RedisTemplate redisTemplate;

    @GetMapping({"/","/index.html"})
    public String indexPage(Model model){
        //TODO:查出所有的一级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();
        //视图解析器进行拼串
        //thymeleaf默认配置了前缀和后缀
        model.addAttribute("categorys",categoryEntities);
        return "index";
    }
    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatalogJson()
    {
        Map<String, List<Catelog2Vo>> map = categoryService.getCatalogJson();
        return map;
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello()
    {
        //获取一把锁，只要锁名字一样，就是同一把锁
        RLock lock = redissonClient.getLock("my-lock");
        //加锁
        //1、锁的自动续期，如果业务超长，运行期间自动给锁续上新的30s,不用担心业务时间过长，锁自动过期删掉
        //2、加锁的业务只要运行完成，就不会给当前业务续期，即使不手动释放锁，锁默认30s后自动删除
        lock.lock(10, TimeUnit.SECONDS); //10秒后自动解锁，自动解锁时间一定要大于业务的执行时间，锁时间到期之后不再自动续期
        lock.lock(); //阻塞式等待，默认加的锁都是30s
        //1、如果指定了超时时间，就发送给redis执行脚本，进行占锁，默认超时就是我们指定的时间
        //2、如果我们未指定锁的超时时间，就是用30*1000（30s）【看门狗的默认时间】
        //   占锁成功就会启动一个定时任务【重新给锁设置过期时间30s】
        //   internalLockeastTime[看门狗时间]/3，10s执行一次定时任务

        try {
            Thread.sleep(30000);
            System.out.println("加锁成功，执行业务");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("释放锁..."+Thread.currentThread().getId());
            lock.unlock();
        }
        return "hello";
    }



    @ResponseBody
    @GetMapping("/write")
    public String write()
    {
        String s="";
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("rw-lock");
        RLock rLock = readWriteLock.writeLock();
        rLock.lock();
        try {
            s = UUID.randomUUID().toString();
            //Thread.sleep(30000);
            redisTemplate.opsForValue().set("writeValue",s);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }
        return s;
    }

    @ResponseBody
    @GetMapping("/read")
    public String read()
    {
        String s="";
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("rw-lock");
        RLock rLock = readWriteLock.readLock();
        rLock.lock();
        try {
            Thread.sleep(30000);
            s = (String) redisTemplate.opsForValue().get("writeValue");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }
        return s;
    }

    @ResponseBody
    @GetMapping("/qz")
    public String qz()  {
        RSemaphore count = redissonClient.getSemaphore("count");
        try {
            count.tryAcquire();
            System.out.println("成功抢占车位");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "成功抢占车位";
    }

    @ResponseBody
    @GetMapping("/sf")
    public String sf()  {
        RSemaphore count = redissonClient.getSemaphore("count");
        try {
            count.release();
            System.out.println("成功释放车位");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "成功释放车位";
    }

    @ResponseBody
    @GetMapping("/cd")
    public String cd() throws InterruptedException {
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.trySetCount(5);
        door.await();//等待闭锁完成,必须执行5次go方法，执行5次door.countDown();这里才继续执行
        System.out.println("人都走光了，锁门");
        return "人都走光了，关门。。";
    }

    @ResponseBody
    @GetMapping("/go")
    public String go() throws InterruptedException {
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.countDown();
        System.out.println("走了一个");
        return "走了一个";
    }


}
